package fangbing.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.springframework.stereotype.Service;

import fangbing.model.vo.Events;
import fangbing.model.vo.MenstruationBaseVo;
import fangbing.util.common.StaticTool;

@Service("MenstruationAlgorithmService")
public class MenstruationAlgorithmServiceImpl implements
		MenstruationAlgorithmService {

	@Override
	public int daysBetween(String firstDate, String nowDate) throws ParseException{
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        Calendar cal = Calendar.getInstance();    
        cal.setTime(sdf.parse(firstDate));    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(sdf.parse(nowDate));    
        long time2 = cal.getTimeInMillis();         
        long between_days=(time2-time1)/(1000*3600*24);  
            
       return Integer.parseInt(String.valueOf(between_days));
	}

	/**
	 * 参数：当前日历第一天，月经第一天
	 * 计算每一天的类型
	 * 当前日期每一天与第一次月经的时间差除以周期取余：a
	 * a：0-6 月经期，7-8 安全期，9-18 易孕期，19-27安全期，-1至-9安全期，-10至-19易孕期，-20至-21安全期，-22至-27月经期，14和-14排卵日
	 * */
	public List<Events> getDateType(String startDate,MenstruationBaseVo menstruationBaseVo) throws ParseException{
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		List<Events> eventSList= new ArrayList<Events>();
		//循环出当前日历页每一天
		for(int i=0;i<StaticTool.CALENDARCIRCLE;i++){
			Calendar cal = Calendar.getInstance();
			cal.setTime(sdf.parse(startDate));
			cal.add(Calendar.DATE, i);
			//第一次月经与每一天的日期差
			int dayCount = daysBetween(menstruationBaseVo.getNearMenstruationFirstDay(),sdf.format(cal.getTime()));
			//余数
			int remainder = dayCount%menstruationBaseVo.getCycleNumOfDay();
			Events events = new Events();
			events.setStart(sdf.format(cal.getTime()));
			events.setEnd(sdf.format(cal.getTime()));
			
			if(remainder>=0&&remainder<=6||remainder>=-27&&remainder<=-22){
				events.setTitle("月经期");
				events.setColor(StaticTool.PINK);
			}else if(remainder==8||remainder==7||remainder==-20||remainder==-21||remainder>=19&&remainder<=27||remainder>=-9&&remainder<=-1){
				events.setTitle("安全期");
				events.setColor(StaticTool.GREEN);
			}else if(remainder>=9&&remainder<=18||remainder>=-19&&remainder<=-10){
				events.setTitle("易孕期");
				events.setColor(StaticTool.PURPLE);
			}else{
				events.setTitle("");
			}
			eventSList.add(events);
			
			if(remainder==14||remainder==-14){
				Events pailuanEvents = new Events();
				pailuanEvents.setStart(sdf.format(cal.getTime()));
				pailuanEvents.setEnd(sdf.format(cal.getTime()));
				pailuanEvents.setTitle("排卵日");
				pailuanEvents.setColor(StaticTool.ORANGE);
				eventSList.add(pailuanEvents);
			}
		}
		
		
		return eventSList;
	}
	
	
	
	
	
	
	


}
